package com.sy.exception.resolver;

import com.sy.dto.JsonResult;
import com.sy.utils.HttpUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Monkey-D-Gu
 * @version 1.0
 * @date 2020/9/11 0011 10:21
 * @usage Spring的全局异常处理器
 */

public class GlobalExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse resp, Object o, Exception e) {
        System.out.println("异常处理器处理异常...");
        if (o instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) o;
            System.out.println("出现异常的Controller控制器为：" + handlerMethod.getBean());
            System.out.println("出现异常的Controller控制器方法为：" + handlerMethod.getMethod());
        }
        if (null != e) {
            //打印异常信息到控制台
            System.out.println("异常信息为：" + e.getMessage());
            try {
                JsonResult jsonResult = JsonResult.buildFailure(500, "后端服务器出现异常");
                HttpUtils.writeJson(resp, jsonResult);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return null;
    }
}
